/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "cJSON.h"
#include "ohos_init.h"
#include "log.h"

#include <cmsis_os2.h>
#include "ext_dev_if.h"
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define LOG_D(fmt, ...) HILOG_DEBUG(HILOG_MODULE_APP, fmt, ##__VA_ARGS__)
#define LOG_W(fmt, ...) HILOG_WARN(HILOG_MODULE_APP, fmt, ##__VA_ARGS__)
#define LOG_I(fmt, ...) HILOG_INFO(HILOG_MODULE_APP, fmt, ##__VA_ARGS__)
#define LOG_E(fmt, ...) HILOG_ERROR(HILOG_MODULE_APP, fmt, ##__VA_ARGS__)
#define DBG_ASSERT(cond)                                                             \
    do {                                                                             \
        if (!(cond)) {                                                               \
            HILOG_ERROR("%s:%d '%s' assert failed.\r\n", __FILE__, __LINE__, #cond); \
            while (1)                                                                \
                ;                                                                    \
        }                                                                            \
    } while (0)


static int g_recvJsDataFlag = 0;

static int JsGetClang(const char *key, char *value)
{
    char buf[1024] = {0};

    memset(buf, 0, sizeof(buf));

    if(0 != g_recvJsDataFlag){
        memcpy(buf, "{\"ResponseFromC\":\"Hello World from BES2600!\"}", strlen("{\"ResponseFromC\":\"Hello World from BES2600!\"}") + 1);
        buf[strlen("{\"ResponseFromC\":\"Hello World from BES2600!\"}")] = '\0';
    }
    memcpy(value, buf, strlen(buf) + 1);
    return 0;
}

static int JsSetClang(const char *key, char *value)
{
    if (NULL == key || NULL == value) {
        return -1;
    }
    if ((0 == strcmp(key, "JsAction")) && (0 == strcmp(value, "Hello World"))) {
        g_recvJsDataFlag = !g_recvJsDataFlag;
        LOG_I("Get JS string information -> %s.\r\n", value);
    }
    return 0;
}

/**
 * @brief IoT Main Entry of the IoT-Flower project
 */
static void IotMainEntry(void)
{
    int i = 0;
    JsGetClangFuncationRegister(JsGetClang);
    JsSetClangFuncationRegister(JsSetClang);
    ExtDevSg90Init();
    while (1) {
        LOG_I("angle : %d.", i);
        ExtDevSetSg90Angle(i);
        i = (i + 10) % 180;
        osDelay(1000);
    }
    return;
}
// Add the IotMainEntry function to the System Startup Procedure
APP_FEATURE_INIT(IotMainEntry);